package com.tramp.utils;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;
import com.tramp.frame.server.exception.GenericException;

/**
 * Created by chen on 2017/10/22.
 */
public final class ExecutorUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorUtil.class);

	private static final Map<String, ExecutorService> EXECUTOR_SERVICE_MAP = Maps.newHashMap();

	private ExecutorUtil() {
	}

	/**
	 * 获取线程池
	 * @param executorName		线程池名称，一般为类的simpleName
	 * @param corePoolSize		基本线程数
	 * @param maximumPoolSize	最大线程数
	 * @param keepAliveTimeMills	空闲线程存活时长(mills)
	 * @param queueCapacity		最大等待任务数
	 * @return
	 */
	public static ExecutorService getExecutor(String executorName, int corePoolSize, int maximumPoolSize, long keepAliveTimeMills,
			int queueCapacity) {
		if (StringUtils.isBlank(executorName)) {
			LOGGER.warn("executorName is blank");
			throw new GenericException("ExecutorUtil getExecutor fail,executorName is empty!");
		}
		if (!EXECUTOR_SERVICE_MAP.containsKey(executorName)) {
			synchronized (ExecutorUtil.class) {
				if (!EXECUTOR_SERVICE_MAP.containsKey(executorName)) {
					EXECUTOR_SERVICE_MAP.put(executorName, new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTimeMills,
							TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(queueCapacity)));
				}
			}
		}
		return EXECUTOR_SERVICE_MAP.get(executorName);
	}

	/**
	 * 关闭线程池
	 */
	public static synchronized void shutdown() {
		//todo 遍历EXECUTOR_SERVICE_MAP进行关闭

	}
}
